package com.hyjx.framework.uc.role;

import com.hyjx.framework.common.CommonUtil;
import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.service.RightManager;
import com.hyjx.framework.service.UserCenterService;
import com.hyjx.framework.service.extend.IUserExtend;
import com.hyjx.framework.service.model.CacheRole;
import com.hyjx.framework.service.model.CacheUser;
import com.hyjx.framework.uc.menu.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 角色控制器
 *
 * @author Peter
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Resource
    private RoleService service;
    @Resource
    private MenuService menuService;
    
    /**
     * 进入到信息查询页
     *
     * @return
     */
    @RequestMapping(value = "/gotoList", method = RequestMethod.GET)
    public String gotoList(HttpServletRequest request) {
        return "framework/uc/role/list";
    }
    
    /**
     * 执行客户查询操作
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryList", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(RoleModel model, HttpServletRequest request) {
        if ("".equals(model.getOrg_code())) {
            if (UserCenterService.getCurrentUserInfo().isSuperAdmin()) {
            
            } else {
                model.setOrg_code(UserCenterService.getCurrentUserInfo().getOrg_code());
            }
        }
        return service.queryList(model);
    }
    
    /**
     * 跳转到增加页
     *
     * @return
     */
    @RequestMapping(value = "/gotoAdd", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoAdd(HttpServletRequest request) {
        String optType = request.getParameter("optType");
        RoleModel model = new RoleModel();
        model.setRole_id(CommonUtil.getUUID32());
        model.setRole_type("1");
        model.setOrg_code(UserCenterService.getCurrentUserInfo().getDataOrgCode());
        model.setDepart_code(UserCenterService.getCurrentUserDepartCode());
        model.setValidity("Y");
        ModelAndView mav = new ModelAndView("framework/uc/role/add");
        mav.addObject("model", model);
        mav.addObject("optType", optType);
        return mav;
    }
    
    /**
     * 增加信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public String doAdd(HttpServletRequest request, RoleModel model) {
        IUserExtend userExtendService = (IUserExtend) SpringBeanUtil.getBean("userExtendService");
        if (!userExtendService.isRoleNameUnique(model.getRole_id(), model.getRole_name())) {
            return "notunique";
        }
        
        String menuCodes = request.getParameter("menuCodes");
        model.setMenuCodes(menuCodes);
        String orgCodes = request.getParameter("orgCodes");
        model.setOrgCodes(orgCodes);
        if (service.add(model)) {
            RightManager.init(3);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 跳转到修改页
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoEdit", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoEdit(HttpServletRequest request) {
        String optType = request.getParameter("optType");
        String id = request.getParameter("id");
        RoleModel model = service.getInfoById(id);
        String orgCodes = service.getRoleOrgStr(model.getRole_id());
        model.setOrgCodes(orgCodes);
        model.setMenuCodes(service.getRoleMenuStr(model.getRole_id()));
        ModelAndView mav = new ModelAndView("framework/uc/role/add");
        mav.addObject("model", model);
        mav.addObject("optType", optType);
        return mav;
    }
    
    /**
     * 取用户角色对应关系串
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/doRoleMenu", method = RequestMethod.POST)
    @ResponseBody
    public String doRoleMenu(HttpServletRequest request) {
        String roleId = request.getParameter("id");
        String returnStr = service.getRoleMenuStr(roleId);
        return returnStr;
    }
    
    /**
     * 修改信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/doEdit", method = RequestMethod.POST)
    @ResponseBody
    public String doEdit(HttpServletRequest request, RoleModel model) {
        IUserExtend userExtendService = (IUserExtend) SpringBeanUtil.getBean("userExtendService");
        if (!userExtendService.isRoleNameUnique(model.getRole_id(), model.getRole_name())) {
            return "notunique";
        }
        
        String menuCodes = request.getParameter("menuCodes");
        model.setMenuCodes(menuCodes);
        String orgCodes = request.getParameter("orgCodes");
        model.setOrgCodes(orgCodes);
        if (service.edit(model) > 0) {
            RightManager.init(3);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 删除信息
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoDelete", method = RequestMethod.GET)
    @ResponseBody
    public String gotoDelete(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (service.delete(ids) > 0) {
            RightManager.init(3);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 信息查看
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoView", method = RequestMethod.GET)
    public ModelAndView gotoView(HttpServletRequest request) {
        String id = request.getParameter("id");
        RoleModel model = service.getInfoById(id);
        String orgCodes = service.getRoleOrgStr(model.getRole_id());
        model.setOrgCodes(orgCodes);
        model.setMenuCodes(service.getRoleMenuStr(model.getRole_id()));
        ModelAndView mav = new ModelAndView("framework/uc/role/view");
        mav.addObject("model", model);
        return mav;
    }
    
    /**
     * 角色对应用户设置
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoRoleUser", method = RequestMethod.GET)
    public ModelAndView gotoRoleUser(HttpServletRequest request) {
        String id = request.getParameter("id");
        RoleModel model = service.getInfoById(id);
        if ("1".equals(model.getRole_type())) {
            model.setRoleTypeName("功能");
        } else {
            model.setRoleTypeName("数据");
        }
        String orgCode = model.getOrg_code();
        if (orgCode != null && !"".equals(orgCode)) {
            model.setOrg_name(RightManager.getDepartByCode(orgCode).getDepart_name());
        }
        ModelAndView mav = new ModelAndView("framework/uc/role/roleuser");
        mav.addObject("model", model);
        
        CacheRole cacheRole = RightManager.getSysRoles().get(id);
        if (cacheRole != null) {
            String userIds = cacheRole.getUserIds();
            String[] userIdArray = userIds.split(",");
            StringBuffer sb = new StringBuffer();
            for (String userId : userIdArray) {
                if (!"".equals(userId)) {
                    
                    CacheUser cacheUser = RightManager.getSysUsers().get(userId);
                    if (cacheUser == null || cacheUser.getUser() == null)
                        continue;
                    if (cacheUser.getUser().getValidity().equals("N"))
                        continue;
                    String userName = cacheUser.getUser().getUser_name();
                    String pId = cacheUser.getUser().getDepart_code();
                    sb.append("{id:'" + userId + "',name:'" + userName + "',pId:'" + pId + "'},");
                }
            }
            if (sb.toString().endsWith(","))
                mav.addObject("userInfos", sb.substring(0, sb.length() - 1));
            else
                mav.addObject("userInfos", sb.toString());
        }
        return mav;
    }
    
    /**
     * 删除信息
     * request
     *
     * @return
     */
    @RequestMapping(value = "/saveRoleUser", method = RequestMethod.POST)
    @ResponseBody
    public String saveRoleUser(HttpServletRequest request) {
        String id = request.getParameter("id");
        String ids = request.getParameter("ids");
        
        if (service.saveRoleUser(id, ids)) {
            RightManager.init(3);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 生成树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/doMenuTree", produces = "application/json; charset=utf-8", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String doMenuTree(HttpServletRequest request) {
        String checked = request.getParameter("checked");
        String showOperate = request.getParameter("showOperate");
        String applyRight = request.getParameter("applyRight");
        String showSystemId = request.getParameter("showSystemId");
        if ("all".equals(request.getParameter("showAll")))//包含无效菜单
            return menuService.buildMenuTree(checked, showOperate, applyRight, showSystemId);
        else
            return menuService.buildMenuTreeByCache(checked, showOperate, applyRight, showSystemId);//不包含无效菜单
    }
}